# 构建和测试脚本
# 用于验证项目是否能正常构建和运行

param(
    [switch]$SkipBuild = $false,
    [switch]$SkipTest = $false,
    [switch]$Verbose = $false
)

$ErrorActionPreference = "Stop"

Write-Host "=== AuthService 构建和测试脚本 ===" -ForegroundColor Green

# 获取项目根目录
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$rootDir = Split-Path -Parent $scriptDir
Set-Location $rootDir

Write-Host "项目根目录: $rootDir" -ForegroundColor Yellow

try {
    # 1. 清理之前的构建
    if (-not $SkipBuild) {
        Write-Host "`n1. 清理项目..." -ForegroundColor Blue
        dotnet clean --verbosity minimal
        
        if ($LASTEXITCODE -ne 0) {
            throw "项目清理失败"
        }
    }

    # 2. 还原NuGet包
    if (-not $SkipBuild) {
        Write-Host "`n2. 还原NuGet包..." -ForegroundColor Blue
        dotnet restore
        
        if ($LASTEXITCODE -ne 0) {
            throw "NuGet包还原失败"
        }
    }

    # 3. 构建解决方案
    if (-not $SkipBuild) {
        Write-Host "`n3. 构建解决方案..." -ForegroundColor Blue
        if ($Verbose) {
            dotnet build --configuration Release --verbosity normal
        } else {
            dotnet build --configuration Release --verbosity minimal
        }
        
        if ($LASTEXITCODE -ne 0) {
            throw "项目构建失败"
        }
        
        Write-Host "✅ 构建成功!" -ForegroundColor Green
    }

    # 4. 检查项目结构
    Write-Host "`n4. 检查项目结构..." -ForegroundColor Blue
    
    $projects = @(
        "AuthService.Api",
        "AuthService.Application", 
        "AuthService.Domain",
        "AuthService.Infrastructure"
    )
    
    foreach ($project in $projects) {
        if (Test-Path "$project/$project.csproj") {
            Write-Host "✅ $project - 项目文件存在" -ForegroundColor Green
        } else {
            Write-Host "❌ $project - 项目文件缺失" -ForegroundColor Red
        }
        
        $binPath = "$project/bin/Release/net9.0"
        if (Test-Path $binPath) {
            Write-Host "✅ $project - 构建输出存在" -ForegroundColor Green
        } else {
            Write-Host "❌ $project - 构建输出缺失" -ForegroundColor Red
        }
    }

    # 5. 检查关键文件
    Write-Host "`n5. 检查关键文件..." -ForegroundColor Blue
    
    $keyFiles = @(
        "AuthService.Domain/Entities/User.cs",
        "AuthService.Domain/Entities/DynamicApiEndpoint.cs",
        "AuthService.Infrastructure/Migrations/001_CreateUsersTable.cs",
        "AuthService.Infrastructure/Migrations/002_CreateDynamicApiEndpointsTable.cs",
        "AuthService.Application/Services/DynamicApiService.cs",
        "AuthService.Api/Controllers/HealthController.cs"
    )
    
    foreach ($file in $keyFiles) {
        if (Test-Path $file) {
            Write-Host "✅ $file" -ForegroundColor Green
        } else {
            Write-Host "❌ $file - 文件缺失" -ForegroundColor Red
        }
    }

    # 6. 运行基本测试（如果有测试项目）
    if (-not $SkipTest) {
        Write-Host "`n6. 查找测试项目..." -ForegroundColor Blue
        
        $testProjects = Get-ChildItem -Path . -Filter "*.Tests.csproj" -Recurse
        
        if ($testProjects.Count -gt 0) {
            Write-Host "找到 $($testProjects.Count) 个测试项目" -ForegroundColor Yellow
            
            foreach ($testProject in $testProjects) {
                Write-Host "运行测试: $($testProject.Name)" -ForegroundColor Blue
                dotnet test $testProject.FullName --configuration Release --verbosity minimal
                
                if ($LASTEXITCODE -ne 0) {
                    Write-Host "⚠️ 测试失败: $($testProject.Name)" -ForegroundColor Yellow
                } else {
                    Write-Host "✅ 测试通过: $($testProject.Name)" -ForegroundColor Green
                }
            }
        } else {
            Write-Host "未找到测试项目" -ForegroundColor Yellow
        }
    }

    # 7. 检查配置文件
    Write-Host "`n7. 检查配置文件..." -ForegroundColor Blue
    
    $configFiles = @(
        "AuthService.Api/appsettings.json",
        "AuthService.Api/appsettings.Development.json"
    )
    
    foreach ($configFile in $configFiles) {
        if (Test-Path $configFile) {
            Write-Host "✅ $configFile" -ForegroundColor Green
            
            # 检查配置文件是否为有效JSON
            try {
                $content = Get-Content $configFile -Raw
                $json = ConvertFrom-Json $content
                Write-Host "  ✅ JSON格式有效" -ForegroundColor Green
            } catch {
                Write-Host "  ❌ JSON格式无效: $($_.Exception.Message)" -ForegroundColor Red
            }
        } else {
            Write-Host "❌ $configFile - 配置文件缺失" -ForegroundColor Red
        }
    }

    # 8. 生成构建报告
    Write-Host "`n8. 生成构建报告..." -ForegroundColor Blue
    
    $report = @{
        BuildTime = Get-Date
        Success = $true
        Projects = $projects.Count
        KeyFiles = $keyFiles.Count
    }
    
    $reportJson = $report | ConvertTo-Json -Depth 2
    $reportPath = "build-report.json"
    $reportJson | Out-File -FilePath $reportPath -Encoding UTF8
    
    Write-Host "构建报告已保存到: $reportPath" -ForegroundColor Green

    Write-Host "`n=== 构建完成 ===" -ForegroundColor Green
    Write-Host "✅ 所有检查通过!" -ForegroundColor Green
    Write-Host "项目已准备就绪，可以运行:" -ForegroundColor Yellow
    Write-Host "  cd AuthService.Api" -ForegroundColor Cyan
    Write-Host "  dotnet run" -ForegroundColor Cyan

} catch {
    Write-Host "`n❌ 构建失败: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "请检查错误信息并修复问题后重试。" -ForegroundColor Yellow
    exit 1
}

Write-Host "`n构建脚本执行完成!" -ForegroundColor Green
